<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { UserInfo, AuthorityInfo } from '@/types/user'
import { ElNotification, ElMessageBox } from 'element-plus'
import { ref, onMounted, watch } from 'vue'
import {
  getUserInfo,
  updateAuthorityInfo,
  lockdown,
  unlockdown
} from '@/api/user'
import { formatBirthday } from '@/utils/format'

// 获取用户数据
const userData = ref<UserInfo[]>([])
const authorityData = ref<AuthorityInfo[]>([])
const authorityDetail = ref<AuthorityInfo>({} as AuthorityInfo)
const loading = ref(false)
// 分页
const total = ref(0)
const params = ref({
  // 当前页
  page: 1,
  // 当前生效的每页条数
  pageSize: 10,
  // 审核状态
  status: ''
})
// 条件查询
const options = [
  {
    value: 0,
    label: '封禁'
  },
  {
    value: 1,
    label: '正常'
  },
  {
    value: 2,
    label: '注销'
  }
]
const getUser = async () => {
  loading.value = true
  const result = await getUserInfo(params)
  userData.value = result.data
  // @ts-ignore
  total.value = result.total
  userData.value.map((item: UserInfo) => {
    if (item.birthday) {
      item.birthday = formatBirthday(item.birthday)
    }
  })
  for (let i = 0; i < userData.value.length; i++) {
    authorityData.value[i] = userData.value[i].authority
  }
  authorityData.value.forEach((item) => {
    const dateNow = new Date()
    const time = new Date(item.time)
    if (dateNow > time) {
      item.time = ''
    }
  })
  loading.value = false
}
const handleSizeChange = (size: number) => {
  params.value.page = 1
  params.value.pageSize = size
  getUser()
}
const handleCurrentChange = (value: number) => {
  params.value.page = value
  getUser()
}
const searchBtn = () => {
  getUser()
}
const resetBtn = () => {
  params.value.status = ''
  getUser()
}

// 修改权限Dialog弹层
const isShowAuthorityDialog = ref(false)
const updateAuthority = (row: AuthorityInfo) => {
  isShowAuthorityDialog.value = true
  authorityDetail.value = row
}
// 更改date-picker的状态
const datePickerState = ref(true)
const updatePickerState = () => {
  if (
    authorityDetail.value.articles &&
    authorityDetail.value.videos &&
    authorityDetail.value.likes &&
    authorityDetail.value.comments &&
    authorityDetail.value.rewards &&
    authorityDetail.value.attentions
  ) {
    datePickerState.value = true
  } else {
    datePickerState.value = false
  }
}

// 修改权限
const formRef = ref<FormInstance>()
// 自定义校验规则
const checkDate = (_: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请选择处罚截止日期'))
  } else if (new Date(value) < new Date()) {
    callback(new Error('处罚截止日期不能小于当前日期'))
  } else {
    callback()
  }
}
// 规则校验
const rules = ref<FormRules<AuthorityInfo>>({
  time: [{ validator: checkDate, trigger: 'blur' }]
})
// 修改权限
const updateAuthorityBtn = async (formEl: FormInstance | undefined) => {
  if (datePickerState.value) {
    authorityDetail.value.time = ''
    await updateAuthorityInfo(authorityDetail.value)
    isShowAuthorityDialog.value = false
    ElNotification({
      title: '温馨提示',
      message: '修改权限成功',
      type: 'success',
      duration: 1500
    })
    getUser()
  } else {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        await updateAuthorityInfo(authorityDetail.value)
        isShowAuthorityDialog.value = false
        ElNotification({
          title: '温馨提示',
          message: '修改权限成功',
          type: 'success',
          duration: 1500
        })
        getUser()
      }
    })
  }
}

// 封禁账号
const lock = async (id: number) => {
  await ElMessageBox.confirm('你确定要封禁该用户吗？', '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await lockdown(id)
  ElNotification({
    title: '温馨提示',
    message: '封禁成功',
    type: 'success',
    duration: 1500
  })
  getUser()
}

// 解封账号
const unlock = async (id: number) => {
  await ElMessageBox.confirm('你确定要解封该用户吗？', '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await unlockdown(id)
  ElNotification({
    title: '温馨提示',
    message: '解封成功',
    type: 'success',
    duration: 1500
  })
  getUser()
}

watch(
  authorityDetail,
  () => {
    updatePickerState()
  },
  { deep: true }
)

onMounted(() => {
  getUser()
})
</script>

<template>
  <page-container title="用户管理">
    <!-- 表单 -->
    <el-form>
      <el-form-item label="账号状态：">
        <el-select
          v-model="params.status"
          placeholder="请选择"
          style="width: 240px; margin-right: 20px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="searchBtn">搜索</el-button>
        <el-button @click="resetBtn">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="userData" v-loading="loading" style="width: 100%">
      <el-table-column type="index" label="序号" width="100" align="center" />
      <el-table-column label="头像" align="center" width="200">
        <template #default="{ row }">
          <el-image :src="row.avatar" class="avatar" v-if="row.avatar" />
          <img src="@/assets/default_avatar.png" class="avatar" v-else />
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center" width="200">
        <template #default="{ row }">
          <span>{{ row.nickname || row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" width="200">
        <template #default="{ row }">
          <span v-if="row.gender === 0">未设置</span>
          <span v-if="row.gender === 1">男</span>
          <span v-if="row.gender === 2">女</span>
        </template>
      </el-table-column>
      <el-table-column label="生日" align="center" width="200">
        <template #default="{ row }">
          <span class="text">{{ row.birthday || '未设置' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="简介" align="center">
        <template #default="{ row }">
          <span class="text">{{ row.introduction || '未设置' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <template v-if="row.state === 2">
            <el-button type="primary" disabled link>已注销</el-button>
          </template>
          <template v-else>
            <el-button
              type="primary"
              :disabled="!row.state"
              link
              @click="updateAuthority(row.authority)"
              >修改权限</el-button
            >
            <el-button
              type="primary"
              :disabled="!row.state"
              link
              @click="lock(row.user_id)"
              >封禁</el-button
            >
            <el-button
              type="primary"
              :disabled="row.state"
              link
              @click="unlock(row.user_id)"
              >解封</el-button
            >
          </template>
        </template>
      </el-table-column>
      <!-- 暂无数据 -->
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </el-table>

    <!-- 分页 -->
    <el-row
      style="display: flex; justify-content: end"
      v-if="userData.length > 0"
    >
      <el-pagination
        v-model:current-page="params.page"
        v-model:page-size="params.pageSize"
        :page-sizes="[2, 3, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px"
      />
    </el-row>
  </page-container>

  <!-- 修改权限Dialog弹层 -->
  <el-dialog v-model="isShowAuthorityDialog" title="修改权限" width="666">
    <el-form
      autocomplete="off"
      ref="formRef"
      :model="authorityDetail"
      :rules="rules"
    >
      <el-row
        style="display: flex; justify-content: center; margin-bottom: 10px"
      >
        <el-checkbox label="发布文章" v-model="authorityDetail.articles" />
        <el-checkbox label="发布视频" v-model="authorityDetail.videos" />
        <el-checkbox label="点赞" v-model="authorityDetail.likes" />
        <el-checkbox label="评论" v-model="authorityDetail.comments" />
        <el-checkbox label="打赏" v-model="authorityDetail.rewards" />
        <el-checkbox label="关注" v-model="authorityDetail.attentions" />
      </el-row>

      <el-row style="display: flex; justify-content: center">
        <el-form-item prop="time">
          <el-date-picker
            type="datetime"
            placeholder="请选择处罚截止日期"
            :disabled="datePickerState"
            v-model="authorityDetail.time"
          />
        </el-form-item>
      </el-row>

      <el-row>
        <el-col
          :span="12"
          style="display: flex; justify-content: end; padding-right: 5px"
        >
          <el-button type="primary" @click="updateAuthorityBtn(formRef)"
            >确认</el-button
          >
        </el-col>
        <el-col :span="12" style="padding-left: 5px">
          <el-button @click="isShowAuthorityDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<style scoped lang="scss">
.text {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.avatar {
  width: 36px;
  height: 36px;
  border-radius: 18px;
}
.btn {
  margin-top: 20px;
  background-color: aqua;
}
</style>
